package com.ww.juc.forkjoin;

import java.util.Random;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

public class ArraySum {

    public static void main(String[] args) {
        // 创建2000个随机数组成的数组:
        long[] array = new long[2000];
        for (int i = 0; i < array.length; i++) {
            array[i] = random();
        }

        ForkJoinTask<Long> task = new SumTask(array, 0, array.length);
        Long result = ForkJoinPool.commonPool().invoke(task);
        System.out.println("计算结果：" + result);
    }

    static Random random = new Random(0);

    static long random() {
        return random.nextInt(10000);
    }
}

/**
 * 继承自RecursiveTask，在compute()方法中，关键是如何“分裂”出子任务并且提交子任务
 */
class SumTask extends RecursiveTask<Long> {

    private static final long serialVersionUID = 1263524939360642008L;

    static final int THRESHOLD = 500;

    long[] array;

    int start;

    int end;

    SumTask(long[] array, int start, int end) {
        this.array = array;
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        if (end - start < THRESHOLD) {
            // 任务足够小，直接计算
            long sum = 0;
            for (int i = start; i < end; i++) {
                sum += array[i];
            }
            return sum;
        }

        // 拆分任务
        int middle = (end + start) / 2;

        SumTask sumTask1 = new SumTask(array, start, middle);
        SumTask sumTask2 = new SumTask(array, middle, end);

        // invokeAll会并行运行两个子任务
        invokeAll(sumTask1, sumTask2);

        // 得到子任务结果
        Long subResult1 = sumTask1.join();
        Long subResult2 = sumTask2.join();

        // 汇总结果
        Long result = subResult1 + subResult2;

        return result;
    }
}